package com.sophie.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 工具类，用于生成验证码
 */
@WebServlet(name = "GifCaptchaUtil", value = "/GifCaptchaUtil")
public class GifCaptchaUtil extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.借助与HuTool工具类
        GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(80, 40);
        //2.设置响应内容 content-type (请求这个Servlet，传递给浏览器的是一张图片)
        response.setContentType("image/gif");
        //3.不缓存
        response.setHeader("Pragma", "No-cache");
        //4.获取图片上文字
        String code = gifCaptcha.getCode();
        //5.!!!!!重点，如果其他的Servlet想要获取这个验证码的值，怎么办？
        //解决办法是：将code存入session，只要是同一个会话都可以获取
        HttpSession session = request.getSession();
        session.setAttribute("autoCode",code);
        //6.将图片使用流写给页面
        gifCaptcha.write(response.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}